import { Sendcontracts } from "@/components/form/contracts/send.contracts"
import { FormModal } from "@/components/modal/form.modal"
import { Field_Search } from "@/components/utils/field.list"
import contractService from "@/services/contract.service"
import { StoreContext } from "@/store"
import { AsyncModal, OperateRender, IndexRender, FormRender, ListTable, DateRender } from "@whzhuke/antd"
import { useMobx } from "@whzhuke/mobx"
import { Button, Col, Modal, Row, Space } from "antd"
import { useForm } from "antd/es/form/Form"
import React, { useCallback, useContext } from "react"
import { EditContracts } from "@/components/form/contracts/edit.contracts"
import { functionCommon } from "@whzhuke/common"

const Page = useMobx(() => {
  const [form] = useForm()
  const { ListStore } = useContext(StoreContext)
  const titleRender = useCallback(() => {
    return (
      <Row justify="space-between" align="middle">
        <Col> </Col>
        <Col>
          <Space size="middle">
            <Button type="primary" onClick={AddModal()}>
              添加
            </Button>
            <Button type="primary" onClick={Zanwu()}>
              导出
            </Button>
          </Space>
        </Col>
      </Row>
    )
  }, [])
  const Zanwu = useCallback(() => async () => {}, [])
  const AddModal = useCallback(
    (value?: any) => async () => {
      const done = await AsyncModal({
        content: FormModal,
        params: {
          formProps: {
            value: { ...value }
          },
          formEle: EditContracts,
          title: "添加合同"
        }
      })
      if (done) {
        ListStore.updateList(contractService.list)
      }
    },
    []
  )

  const onFinish = useCallback(data => {
    const [start, end] = data.range || []
    data.startTime = start ? new Date(start).getTime() : undefined
    data.endTime = end ? new Date(end).getTime() : undefined
    delete data.range
    ListStore.setParams(contractService.list, data)
  }, [])

  const SendModal = useCallback(
    (val?, item?) => async () => {
      const done = await AsyncModal({
        content: FormModal,
        params: {
          formEle: Sendcontracts,
          formProps: {
            values: item,
            service: contractService
          },
          title: "发送合同"
        }
      })
      if (done) {
        ListStore.updateList(contractService.list)
      }
    },
    []
  )

  const previewContract = useCallback((fileUrl?: string) => {
    if (!fileUrl) {
      Modal.warning({
        title: "提示",
        content: "暂无可预览的合同文件"
      })
      return
    }

    const viewerOrigin = window.location.origin
    const previewBase = `${viewerOrigin}/web/viewer.html?file=`
    const normalizedUrl = functionCommon.requestHost("public") + fileUrl
    const previewUrl = `${previewBase}${encodeURIComponent(normalizedUrl)}`
    window.open(previewUrl, "_blank")
  }, [])

  const renderFileUrl = useCallback(
    (_: string, item: any) => {
      const rawUrl = item?.fileUrl
      if (!rawUrl) return "-"

      const extTarget = rawUrl.split("?")[0]?.toLowerCase() || ""
      const isPdf = extTarget.endsWith(".pdf")

      if (isPdf) {
        return (
          <Button type="link" onClick={() => previewContract(rawUrl)}>
            预览
          </Button>
        )
      }

      const downloadUrl = functionCommon.requestHost("public") + rawUrl
      return downloadUrl ? (
        <a href={downloadUrl} target="_blank" rel="noopener noreferrer">
          下载
        </a>
      ) : (
        "-"
      )
    },
    [previewContract]
  )
  return (
    <Row>
      <Col span={24}>
        <FormRender
          form={form}
          onFinish={onFinish}
          layout="inline"
          fieldList={[
            {
              fieldType: "rangeDate",
              formItemConfig: {
                name: "range",
                label: "创建时间"
              },
              config: {
                showTime: !0,
                format: "YYYY-MM-DD HH:mm:ss"
              }
            },
            {
              fieldType: "input",
              formItemConfig: {
                label: "合同编号",
                name: "code"
              },
              config: {
                placeholder: "合同编号"
              }
            },
            {
              fieldType: "input",
              formItemConfig: {
                label: "合同名称",
                name: "name"
              },
              config: {
                placeholder: "合同名称"
              }
            },

            Field_Search
          ]}
        />
      </Col>
      <Col span={24}>
        <ListTable
          title={titleRender}
          apiColumns={[
            IndexRender("id", 80),
            ["fileUrl", "合同地址", renderFileUrl],
            ["code", "合同编号"],
            ["name", "合同名称"],
            ["updatedBy", "修改人"],
            ["updateTs", "修改时间", DateRender()],
            ["createTs", "创建时间", DateRender()],
            ["id", "操作", OperateRender([["发送", SendModal]]), { width: 80, fixed: "right" }]
          ]}
          apiService={contractService.list}
        />
      </Col>
    </Row>
  )
})

export default Page
